package com.minelx.woods.task.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minelx.sqlstructures.common.Files;
import com.minelx.sqlstructures.statements.clause.Field;
import com.minelx.woods.task.core.values.FieldPathValues;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class FieldFactory {
	private final JSONObject schemas;

	public FieldFactory() {
		schemas = JSON.parseObject(Files.toString(Objects.requireNonNull(FieldFactory.class.getResourceAsStream("/FieldFactory.json")), StandardCharsets.UTF_8));
	}

	public Field createField(FieldPathValues tableAndField) {
		String fieldName = tableAndField.getFieldName();
		String comment = commentOf(tableAndField);
		String schemaName = tableAndField.getTableName() + "." + fieldName;
		if (schemas.containsKey(schemaName)) {
			String formation = (String) schemas.get(schemaName);
			return Field.as(formation.replace("$value$", fieldName), comment);
		} else {
			return Field.as(fieldName, comment);
		}
	}

	private String commentOf(FieldPathValues tableAndField) {
		String comment = tableAndField.getComment();
		if (comment.isBlank()) {
			return tableAndField.getTableName() + "." + tableAndField.getFieldName();
		}
		return comment;
	}
}